package com.neusoft.tijian.aop;

import com.alibaba.fastjson.JSONObject;
import com.neuedu.utils.JwtUtils;
import com.neusoft.tijian.mapper.OperateLogMapper;
import com.neusoft.tijian.mapper.UsersMapper;
import com.neusoft.tijian.po.OperateLog;
import com.neusoft.tijian.po.Users;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    OperateLogMapper mapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    UsersMapper usersMapper;

    @Around("@annotation(com.neusoft.tijian.aop.Log)")
    public Object insertLog(ProceedingJoinPoint pjp) throws Throwable {
        OperateLog operateLog ;
        String realName;
        String id;

        //起始时间
        long start = System.currentTimeMillis();

        //操作放行
        Object result = pjp.proceed();

        //结束时间
        long end = System.currentTimeMillis();

        //获取操作日志参数
        long costTime = end - start;
        String jwt = request.getHeader("token");

        if (!StringUtils.hasLength(jwt)){
            Object[] arg = pjp.getArgs();
            String string = Arrays.toString(arg);
            Users user = (Users) arg[0];
            id = user.getUserId();
            realName = usersMapper.getNameById(id);
        }else {
            jwt = jwt.replaceAll("\"","");
            Claims claims = JwtUtils.parseJWT(jwt);
            realName =(String) claims.get("realName");
            id = (String) claims.get("id");
        }



        LocalDateTime nowTime = LocalDateTime.now();
        String className = pjp.getTarget().getClass().getName();
        String methodName = pjp.getSignature().toString();
        Object[] args = pjp.getArgs();

        operateLog = new OperateLog(null,id,realName,nowTime,className,methodName, Arrays.toString(args), JSONObject.toJSONString(result),costTime);
        mapper.insert(operateLog);

        //记录日志
        log.info("AOP记录操作日志：{}",operateLog);

        return result;

    }

}
